import axios from 'axios';
import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

class ErnieService {
    constructor() {
        this.baseURL = 'https://aip.baidubce.com';
        this.accessToken = null;
        this.tokenExpireTime = null;
    }

    /**
     * 获取访问令牌
     * @param {string} clientId - API Key
     * @param {string} clientSecret - Secret Key
     * @returns {Promise<string>} 访问令牌
     */
    async getAccessToken(clientId, clientSecret) {
        try {
            const response = await axios({
                method: 'POST',
                url: `${this.baseURL}/oauth/2.0/token`,
                proxy: false, // 禁用代理
                params: {
                    grant_type: 'client_credentials',
                    client_id: clientId,
                    client_secret: clientSecret
                }
            });

            if (response.data && response.data.access_token) {
                this.accessToken = response.data.access_token;
                // 设置token过期时间（30天），提前一天刷新
                this.tokenExpireTime = Date.now() + 29 * 24 * 60 * 60 * 1000;
                return response.data;
            } else {
                throw new Error('Invalid response from Baidu API');
            }
        } catch (error) {
            console.error('Error getting access token:', error.response?.data || error.message);
            console.log('Error baidu getToken  request:', error);
            throw error;
        }
    }

    /**
     * 发送聊天请求
     * @param {string} accessToken - 访问令牌
     * @param {Array} messages - 消息数组
     * @param {Object} params - 其他参数
     * @returns {Promise<Object>} 聊天响应
     */
    async chat(accessToken, messages, params = {}) {
        try {
            const response = await axios({
                method: 'POST',
                url: `${this.baseURL}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro`,
                params: { access_token: accessToken },
                headers: {
                    'Content-Type': 'application/json'
                },
                proxy: false, // 禁用代理
                data: {
                    messages,
                    ...params
                }
            });

            return response.data;
        } catch (error) {
            console.error('Error in chat request:', error.response?.data || error.message);
            console.log('Error baidu chatrequest:', error);
            throw error;
        }
    }
}

// 创建单例实例
const ernieService = new ErnieService();
export default ernieService;